﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using SunXNA.RainbowXNA.RenderObject;
using SunXNA.RainbowXNA.Material;

namespace SunXNA.RainbowXNA.Batch
{
    class CAnimatedMaterialBatchRenderer : CMaterialBatchRenderer
    {
        private EffectParameter m_bonesParameter;

        public CAnimatedMaterialBatchRenderer()
            : base()
        {
        }

        public override void Initialise(Effect effect)
        {
            base.Initialise(effect);

            m_bonesParameter = effect.Parameters["Bones"];
        }

        public override void Draw(ref Matrix m4View, ref Matrix m4Projection, ref GraphicsDevice device, ref Dictionary<UInt32, IBaseRenderObject> renderObjects, ref Dictionary<UInt32, Texture2D> textures, UInt32 textureHandle)
        {
            m_viewParameter.SetValue(m4View);
            m_projectionParameter.SetValue(m4Projection);

            m_lightColourParameter.SetValue(Color.White.ToVector4());
            //m_lightColourParameter.SetValue(new Vector4(10.0f, 10.0f, 10.0f, 1.0f));
            m_lightDirectionParameter.SetValue(Vector3.Normalize(new Vector3(-1, -1, -1)));

            if (textureHandle != 0)
            {
                m_textureParameter.SetValue(textures[textureHandle]);
            }
            else
            {
                m_textureParameter.SetValue((Texture2D)null);
            }

            m_effect.Begin();
            {
                foreach (EffectPass pass in m_effect.CurrentTechnique.Passes)
                {
                    pass.Begin();
                    {

                        foreach (CRainbowXNA.CRenderInstance instance in m_batch)
                        {
                            Material.CBaseMaterial currentMaterial = instance.Material;
                            Matrix m4World = instance.World;
                            IBaseRenderObject renderObject = renderObjects[instance.ObjectHandle.UID];

                            CAnimatedMeshPartRenderInstance animatedInstance = instance as CAnimatedMeshPartRenderInstance;

                            m_worldParameter.SetValue(m4World);
                            m_diffuseParameter.SetValue(currentMaterial.Diffuse);
                            m_ambientParameter.SetValue(currentMaterial.Ambient);
                            m_bonesParameter.SetValue(animatedInstance.Parent.AnimationPlayer.GetSkinTransforms());

                            m_effect.CommitChanges();

                            renderObject.Draw(device, m4World, m4View, m4Projection);
                        }

                    }
                    pass.End();
                }
            }
            m_effect.End();
        }
    }
}
